<template>
  <left-slide
    :width="drawerWidth + 'px'"
    :visible.sync="slideLeft"
    :title="operType === 'add' ? '添加字段' : '编辑字段'"
    @saveClick="save"
    @cancelClick="cancelClick"
    :showFooter="true"
  >
    <div class="edit-field" v-if="slideLeft">
      <el-form ref="formRef" :model="form" label-position="top" :rules="rules">
        <el-form-item label="字段类型" prop="type">
          <el-select
            v-model="form.type"
            filterable
            clearable
            collapse-tags
            collapse-tags-tooltip
            style="width: 100%"
            placeholder="请选择字段类型"
            :disabled="type !== 'add'"
            @change="typeChange"
          >
            <el-option v-for="(item, index) in typeChoices" :label="item.label" :value="item.value" :key="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="['radio', 'multi-select'].includes(form.type)" label="样式" prop="style">
          <el-radio-group v-model="form.style" :disabled="type !== 'add'">
            <el-radio :label="item.key" v-for="item in radioChoices" :key="item.key">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="['cascade'].includes(form.type)" label="样式" prop="style">
          <el-radio-group v-model="form.style" :disabled="type !== 'add'">
            <el-radio :label="item.key" v-for="item in cascadeTypeChoices" :key="item.key">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="['datetime', 'datetime-range'].includes(form.type)"
          label="样式"
          prop="style"
          :rules="[{ required: true, trigger: 'change', message: '请选择样式' }]"
        >
          <el-radio-group v-model="form.style" :disabled="type !== 'add'">
            <el-radio :label="item.key" v-for="item in dateTypeChoices" :key="item.key">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="字段名称" prop="name">
          <el-input
            v-model.trim="form.name"
            placeholder="请输入字段名称"
            :maxlength="50"
            clearable
            show-word-limit
            :disabled="form.category === 'system'"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="提示暗文"
          prop="placeholder"
          v-if="
            ['radio', 'multi-select'].includes(form.type)
              ? form.style === 'dropdown'
              : !['number', 'datetime-range'].includes(form.type)
          "
        >
          <el-input
            v-model.trim="form.placeholder"
            placeholder="请输入提示暗文"
            :maxlength="50"
            clearable
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="['cascade'].includes(form.type) && showOption"
          label="层级"
          prop="options.level"
          style="width: 100%"
        >
          <el-select v-model="form.options.level" filterable placeholder="请选择层级" @change="setLevel">
            <el-option :label="item" :value="item" v-for="item in [1, 2, 3, 4, 5]" :key="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="['radio', 'multi-select', 'cascade'].includes(form.type) && showOption">
          <template #label>
            <span style="color: #f56c6c; margin-right: 4px">*</span>
            选项
            <el-tooltip
              :content="form.type === 'cascade' ? '同一父级下子级选项不能重复' : '选项不能重复'"
              placement="top"
              effect="light"
            >
              <i style="color: #b3b9c7; cursor: pointer" class="el-icon-question"></i>
            </el-tooltip>
          </template>
          <selectComp
            @onItemChange="previewChange"
            ref="selectComp"
            v-if="form.type === 'radio'"
            :form="form"
          ></selectComp>
          <Checkbox
            @onItemChange="previewChange"
            ref="MultiSelect"
            v-if="form.type === 'multi-select'"
            :form="form"
          ></Checkbox>
          <Cascader
            ref="Cascader"
            v-if="form.type === 'cascade'"
            :isSave="isSave"
            :form="form"
            @onItemChange="previewChange"
          ></Cascader>
        </el-form-item>
        <!-- 级联单选展示 -->
        <el-form-item
          v-if="['cascade'].includes(form.type) && form.style === 'single'"
          label="层级必选"
          prop="options.fillLevel"
        >
          <el-checkbox v-model="form.options.fillLevel">必选全部层级</el-checkbox>
          <el-tooltip
            content="必选全部层级指当该字段为必填项时候，级联菜单的所有层级都必选，否则不能保存，非必选全部层级指选至任意一级即可"
            placement="top"
            effect="light"
            :show-after="500"
          >
            <i style="color: #b3b9c7; margin-left: 6px; cursor: pointer" class="MC_iconfont el-icon-question"></i>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="效果预览">
          <Preview :form="form" ref="Preview" />
        </el-form-item>
      </el-form>
    </div>
  </left-slide>
</template>
<script>
import leftSlide from '@/components/ui-modules/newConfig/leftSlide.vue'
import { typeArr } from '../utils/utils.js'
import { cloneDeep } from 'lodash'
import Cascader from './cascader.vue'
import selectComp from './select.vue'
import Checkbox from './Checkbox.vue'
import Preview from './Preview.vue'
const defaultForm = {
  field: '',
  type: '',
  name: '',
  placeholder: '',
  style: '',
  choices: [],
  options: {
    children: [],
    fillLevel: false,
    level: 2
  }
}
const getGender = {
  F: '女',
  M: '男',
  N: '保密'
}
export default {
  name: 'addEditFields',
  data() {
    return {
      drawerWidth: 576,
      operType: '',
      slideLeft: false,
      form: cloneDeep(defaultForm),
      typeChoices: typeArr('all'),
      rules: {
        type: [{ required: true, trigger: 'change', message: '请选择字段类型' }],
        name: [{ required: true, trigger: 'blur', message: '请输入字段名称' }],
        style: [{ required: true, trigger: 'change', message: '请选择样式' }],
        'options.level': [{ required: true, trigger: 'change', message: '请选择层级' }]
      },
      type: 'add',
      radioChoices: [
        { label: '下拉菜单', key: 'dropdown' },
        { label: '按钮平铺', key: 'tile' }
      ],
      cascadeTypeChoices: [
        { label: '单选', key: 'single' },
        { label: '多选', key: 'multi' }
      ],
      dateTypeChoices: [
        { label: '年月日', key: 'day' },
        { label: '年月日时分秒', key: 'second' }
      ],
      showOption: true,
      drawerWidth: 576,
      isSave: false
    }
  },
  components: {
    leftSlide,
    Preview,
    Checkbox,
    selectComp,
    Cascader
  },
  props: {
    tableData: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    'form.options.level'(val){
      switch (val) {
          case 1:
            this.drawerWidth = 576
            break
          case 2:
            this.drawerWidth = 576
            break
          case 3:
            this.drawerWidth = 694
            break
          case 4:
            this.drawerWidth = 902
            break
          case 5:
            this.drawerWidth = 1110
            break
          default:
            this.drawerWidth = 576
            break
        }
    }
  },
  methods: {
    cancelClick() {
      this.slideLeft = false
    },
    async openDialog(type, row) {
      this.operType = 'add'
      this.slideLeft = true
      this.isSave = false
      this.type = type // 编辑、新建
      this.form = { ...cloneDeep(defaultForm), ...row }
      this.showOption = true
      if (['radio', 'multi-select', 'cascade'].includes(this.form.type) && type === 'edit') {
        if (row.category === 'system' && !row.choices && !row.options) {
          // 系统预置没有选项的不展示选项
          this.showOption = false
          if (this.form.type === 'cascade') {
            // 系统预置级联特殊处理
            this.form.options = {
              children: [],
              fillLevel: false,
              level: 2
            }
          }
          return
        }
        // 编辑选项回显
        if (this.form.type === 'radio') {
          if (row.field === 'gender') {
            row.choices.map((v) => {
              v.value = getGender[v.key]
            })
          }
          this.$nextTick(() => {
            this.$refs.selectComp &&
              this.$refs.selectComp.setData(row.choices && row.choices.filter((item) => item.isDefault))
          })
        } else if (this.form.type === 'cascade') {
          this.$nextTick(() => {
            this.$refs.Cascader && this.$refs.Cascader.setData(row.options, row.category === 'system')
          })
          this.form.options.fillLevel = Boolean(row.options && row.options.fillLevel)
        }
        this.$nextTick(() => {
          this.previewChange(this.form.type === 'cascade' ? row.options : row.choices)
        })
      }
      this.$nextTick(() => {
        this.$refs['formRef'].clearValidate()
      })
    },
    save() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          this.isSave = true
          const { field, type, name, style, placeholder } = this.form
          let data = { field, type, name, placeholder }
          if (style) {
            // style不存在时不传
            data.style = style
          }
          // 校验选项有没有填
          if (['multi-select', 'radio'].includes(type) && this.showOption) {
            data.choices = this.form.choices.filter((v) => v.value !== '')
            if (data.choices && !data.choices.length) {
              this.$message.error('请填写选项')
              return false
            }
          } else if (['cascade'].includes(type) && this.showOption) {
            // 级联
            if (this.form.options.children && !this.form.options.children.length) {
              this.$message.error('请填写选项')
              return false
            } else {
              data.options = this.form.options
            }
            data.options.fillLevel = this.form.options.fillLevel ? this.form.options.level : 0
          }
          if (this.form._id) {
            data._id = this.form._id
          }
          this.$store.dispatch(data._id ? 'updateGlobalField' : 'createGlobalField', data).then((resp) => {
            if (resp && resp.success) {
              this.$message.success(`${data._id ? '编辑' : '添加'}全局成功`)
              this.$emit('updateSuccess')
              this.operType = ''
              this.slideLeft = false
            }
          })
        }
      })
    },
    setLevel() {
      this.$refs.Cascader.setLevel(this.form.options.level)
    },
    getStyle(type) {
      switch (type) {
        case 'radio':
          return 'dropdown'
        case 'multi-select':
          return 'dropdown'
        case 'cascade':
          return 'single'
        case 'datetime':
          return 'second'
        case 'datetime-range':
          return 'second'
        default:
          return ''
      }
    },
    typeChange(val) {
      // style默认赋值
      this.form.style = this.getStyle(val)
      this.$refs.Preview.setData(this.form.type === 'cascade' ? this.form.options : this.form.choices)
    },
    previewChange(group) {
      this.$refs.Preview.setData(group)
    },
    closeDialog() {
      this.show = false
    }
  }
}
</script>

<style lang="stylus" scoped>
.edit-field {
  margin: 16px
}
</style>
